<script setup>
import {ref, reactive, computed, onMounted} from 'vue'
import {Plus} from '@element-plus/icons-vue'
import axios from "axios";
import {ElMessage} from 'element-plus'

// 筛选表单
const filterForm = reactive({
  searchQuery: '',
  selectedStore: ''
})
// 分页信息
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 100
})
// 弹窗控制
const dialog = reactive({
  addMember: false,
  editMember: false,
  consumption: false,
  points: false,
  recharge: false
})
// 当前操作的会员
const currentMember = ref({})
// 会员表单
const memberForm = ref({
 //  id:'',
 //  memberId:'',
 //  storeId:'',
 //  name:'',
 //  phone:'',
 //  gender:'',
 //  birthday:'',
 // memberLevelId:'',
 //   balance:'',
 //  points:'',
 //   status:'',
 //  createTime:'',
 //   updateTime:'',
 // intType:'',
 // doubleType:'',
 //  varcharType:'',
 //  booleanType:'',
 //  datetimeType:'',
})

// 表格数据
const tableData = ref([])
const selectedItems = ref([])
const selectAll = ref(false)

// 门店选项
const storeOptions = ref([])
//弹窗数据
const consumptionData = ref([])
const pointsData = ref([])
const rechargeData = ref([])

// 计算属性
const filteredData = computed(() => {
  return tableData.value.filter(item => {
    const matchesSearch = item.name.includes(filterForm.searchQuery) ||
        item.phone.includes(filterForm.searchQuery)
    const matchesStore = !filterForm.selectedStore ||
        storeOptions.find(s => s.value === filterForm.selectedStore)?.label === item.store
    return matchesSearch && matchesStore
  })
})
const paginatedData = computed(() => {
  const start = (pagination.pageNum - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  return filteredData.value.slice(start, end)
})
const totalPoints = computed(() => {
  return pointsData.value.reduce((sum, item) => sum + (item.type === 'earn' ? item.points : 0), 0)
})
const usedPoints = computed(() => {
  return pointsData.value.reduce((sum, item) => sum + (item.type === 'use' ? -item.points : 0), 0)
})
const totalRecharge = computed(() => {
  return rechargeData.value.reduce((sum, item) => sum + parseFloat(item.amount.replace('¥', '')), 0)
})
const totalConsumption = computed(() => {
  return consumptionData.value.reduce((sum, item) => sum + parseFloat(item.amount.replace('¥', '')), 0)
})
//综合查询
const handleQuery = () => {
  pagination.pageNum = 1
  fetchData()
}
//分页改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchData()
}
const handleCurrentChange = (val) => {
  pagination.pageNum = val
  fetchData()
}
// 获取门店选项
const fetchStores = async () => {
  try {
    const res = await axios.get('/vip/allStore')
    storeOptions.value = res.data.map(storeId => ({
      value: storeId,
      label: `门店${storeId}` // 根据实际门店名称字段调整
    }))
  } catch (error) {
    ElMessage.error('获取门店列表失败')
  }
}
//获取会员数据
const fetchData = () => {
  try {
    axios.get(`/vip/allVip/${pagination.pageNum}/${pagination.pageSize}`).then((res) => {
      tableData.value = res.data.data
      pagination.total = res.data.total
    })
  } catch (error) {
    ElMessage.error('获取会员数据失败')
  }
}
//全选
const handleSelectionChange = (selection) => {
  selectedItems.value = selection
  selectAll.value = selection.length === paginatedData.value.length
}
const handleSelectAll = (val) => {
  if (val) {
    selectedItems.value = [...paginatedData.value]
  } else {
    selectedItems.value = []
  }
}
//批量删除
const handleBatchDelete = () => {
  try {
    const ids = selectedItems.value.map(item => item.id)
  alert(ids.values)
  axios.post('/vip/deletes', ids).then((res) => {
    if (res.data === ids.length) {
      ElMessage.success(`成功删除${res.data}条记录`)
      fetchData()
      selectedItems.value = []
    }
  })}catch (error) {
  ElMessage.error('删除操作失败')
}
}
//会员弹窗控制
const handleAddMember = () => {
  dialog.addMember = true
}
//会员添加方法
const confirmAddMember = () => {
    axios.post('/vip/sava', memberForm.value).then((res) => {
      ElMessage.success('会员添加成功')
    })
    dialog.addMember = false;
}
//会员编辑弹窗控制
const handleEdit = (row) => {
  currentMember.value = { ...row }
  dialog.editMember = true
}
//会员编辑方法
const confirmEdit = () => {
    axios.post('/vip/update', currentMember.value).then((res) => {
      fetchData()
    })
    dialog.editMember = false
}
// 获取消费记录
const showConsumptionDialog = (row) => {
    axios.get(`/vip/getConsumptionById/${row.id}/${pagination.pageNum}/${pagination.pageSize}`).then((res) => {
      consumptionData.value = res.data.data
      dialog.consumption = true
    })
}
// 获取积分记录
const showPointsDialog = (row) => {
  dialog.points = true
}
// 获取充值记录
const showRechargeDialog = (row) => {
    axios.get(`/vip/MemberRecharge/${row.id}/${pagination.pageNum}/${pagination.pageSize}`).then((res) => {
      rechargeData.value = res.data.data;

    })
  dialog.recharge = true;
}

onMounted(() => {
  fetchData();
  fetchStores();
});
</script>
<template>
  <div class="member-container">
    <!-- 顶部标题 -->
    <div class="header">
      <h1>会员管理</h1>
    </div>
    <!-- 筛选区域 -->
    <div class="filter-container">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item>
          <el-input v-model="filterForm.searchQuery" placeholder="请输入" clearable>
            <template #prepend>
              <span class="input-prepend">会员</span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="filterForm.selectedStore" placeholder="请选择门店" clearable>
            <el-option
                v-for="store in storeOptions"
                :key="store.value"
                :label="store.label"
                :value="store.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button type="primary" @click="fetchData()">刷新</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 操作按钮 -->
    <div class="action-container">
      <el-button type="primary" @click="handleAddMember">
        <el-icon>
          <Plus/>
        </el-icon>
        新增会员
      </el-button>
      <div class="batch-actions">
        <el-checkbox v-model="selectAll" @change="handleSelectAll">全选</el-checkbox>
        <el-button
            type="danger"
            :disabled="!selectedItems.length"
            @click="handleBatchDelete"
        >
          批量删除
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table
          :data="paginatedData"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="id" label="ID" width="80"/>
        <el-table-column prop="name" label="会员名称"/>
        <el-table-column prop="phone" label="手机号" width="150"/>
        <el-table-column prop="storeId" label="所属门店" width="150"/>
        <el-table-column prop="createTime" label="注册日期" width="180"/>
        <el-table-column prop="status" label="状态" width="120">
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="primary" @click="showConsumptionDialog(row)">消费记录</el-button>
            <el-button size="small" type="warning" @click="showPointsDialog(row)">积分</el-button>
            <el-button size="small" type="success" @click="showRechargeDialog(row)">充值记录</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[5,10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
    <!-- 新增会员弹窗 -->
    <el-dialog v-model="dialog.addMember" title="新增会员" width="600px">
      <el-form :model="memberForm" label-width="100px">
        <el-form-item label="会员id" prop="id">
          <el-input v-model="memberForm.memberId" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="会员姓名" prop="name">
          <el-input v-model="memberForm.name" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="门店id" prop="id">
          <el-select v-model="memberForm.storeId" placeholder="请选择门店" style="width:100%">
            <el-option
                v-for="store in storeOptions"
                :key="store.value"
                :label="store.label"
                :value="store.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="会员类别">
          <el-select v-model="memberForm.memberLevelId" placeholder="请选择" style="width:100%">
            <el-option label="普通会员" value=0 />
            <el-option label="黄金会员" value=1 />
            <el-option label="白金会员" value=2 />
          </el-select>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="memberForm.phone" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="memberForm.gender">
            <el-radio label="male" value=1>男</el-radio>
            <el-radio label="female" value=0>女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="生日">
          <el-date-picker
              v-model="currentMember.birthday"
              type="date"
              placeholder="请选择日期"
              style="width:100%"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="memberForm.status">
            <el-radio label="male" value=1>正常</el-radio>
            <el-radio label="female" value=0>不正常</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialog.addMember = false">取消</el-button>
          <el-button type="primary" @click="confirmAddMember">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 编辑会员弹窗 -->
    <el-dialog v-model="dialog.editMember" title="编辑会员" width="600px">
      <el-form :model="currentMember" label-width="100px">
        <el-form-item label="门店">
              <el-select v-model="currentMember.store" placeholder="请选择门店" style="width:100%">
                <el-option
                    v-for="store in storeOptions"
                    :key="store.value"
                    :label="store.label"
                    :value="store.value"
                />
              </el-select>
            </el-form-item>
        <el-form-item label="会员类别">
              <el-select v-model="currentMember.memberType" placeholder="请选择" style="width:100%">
                <el-option label="普通会员" value="normal"/>
                <el-option label="黄金会员" value="gold"/>
                <el-option label="白金会员" value="platinum"/>
              </el-select>
            </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="currentMember.phone" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="currentMember.gender">
            <el-radio label="male" value=1>男</el-radio>
            <el-radio label="female" value=0>女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="生日">
          <el-date-picker
              v-model="currentMember.birthday"
              type="date"
              placeholder="请选择日期"
              style="width:100%"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
              v-model="currentMember.status"
              active-text="启用"
              inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialog.editMember = false">取消</el-button>
          <el-button type="primary" @click="confirmEdit">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 消费记录弹窗 -->
    <el-dialog v-model="dialog.consumption" :title="`${currentMember.name}的消费记录`" width="800px">
      <el-table :data="consumptionData" border style="width: 100%">
        <el-table-column prop="createTime" label="消费日期" width="150"/>
        <el-table-column prop="amount" label="消费金额" width="120"/>
        <el-table-column prop="storeId" label="消费门店"/>
        <el-table-column prop="remark" label="消费项目"/>
        <el-table-column prop="amount" label="获得积分" width="100"/>
      </el-table>
      <template #footer>
        <el-pagination
            small
            layout="prev, pager, next"
            :total="50"
            class="mt-4"
        />
      </template>
    </el-dialog>
    <!-- 积分记录弹窗 -->
    <el-dialog v-model="dialog.points" :title="`${currentMember.name}的积分记录`" width="800px">
      <div class="points-summary">
        <el-statistic title="当前积分" :value="currentMember.points || 0"/>
        <el-statistic title="累计积分" :value="totalPoints"/>
        <el-statistic title="已兑换积分" :value="usedPoints"/>
      </div>
      <el-table :data="pointsData" border class="mt-4" style="width: 100%">
        <el-table-column prop="date" label="日期" width="150"/>
        <el-table-column prop="type" label="类型" width="120">
          <template #default="{ row }">
            <el-tag :type="row.type === 'earn' ? 'success' : 'warning'">
              {{ row.type === 'earn' ? '获得' : '使用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="points" label="积分" width="120"/>
        <el-table-column prop="description" label="说明"/>
      </el-table>
    </el-dialog>
    <!-- 充值记录弹窗 -->
    <el-dialog v-model="dialog.recharge" :title="`${currentMember.name}的充值记录`" width="800px">
      <div class="recharge-summary">
        <el-statistic title="当前余额" :value="currentMember.balance || 0"/>
        <el-statistic title="累计充值" :value="totalRecharge"/>
        <el-statistic title="累计消费" :value="totalConsumption"/>
      </div>
      <el-table :data="rechargeData" border class="mt-4" style="width: 100%">
        <el-table-column prop="rechargeTime" label="充值日期" width="150"/>
        <el-table-column prop="amount" label="充值金额" width="120"/>
        <el-table-column prop="payment" label="支付方式" width="120"/>
        <el-table-column prop="operator" label="操作员"/>
        <el-table-column label="操作" width="120">
          <template #default>
            <el-button size="small" type="text">查看凭证</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<style scoped>
.member-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header {
  margin-bottom: 20px;
}

.header h1 {
  font-size: 20px;
  color: #333;
  margin: 0;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 10px;
}

.action-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.batch-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
}

.points-summary, .recharge-summary {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.el-statistic {
  text-align: center;
}

.mt-4 {
  margin-top: 1rem;
}

.input-prepend {
  padding: 0 10px;
  color: #909399;
}
</style>